package com.review.Test.ThreadPool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class DefinedThreadPool {

	public static void main(String[] args) {

		testBoundThreadPool();
		
		
		//noBoundThreadPool();

	}

	private static void noBoundThreadPool() {
		//无界队列
		ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
		
		for (int i = 0; i < 20; i++) {
			pool.execute(new Job(1));
		}
		pool.shutdown();
	}

	private static void testBoundThreadPool() {
		//拒绝策略
		CallerRunsPolicy callerRunsPolicy = new CallerRunsPolicy();
		//有界队列
		ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 2, 60, TimeUnit.SECONDS, 
				new ArrayBlockingQueue<Runnable>(3), new MyReject());

		Job job1 = new Job(1);
		Job job2 = new Job(2);
		Job job3 = new Job(3);
		Job job4 = new Job(4);
		Job job5 = new Job(5);
		Job job6 = new Job(6);
		
		pool.execute(job1);
		pool.execute(job2);
		pool.execute(job3);
		pool.execute(job4);
		pool.execute(job5);
		pool.execute(job6);
		
		pool.shutdown();
	}

}


class Job implements Runnable{
	
	private static AtomicInteger num = new AtomicInteger();

	private int id;

	public Job(int id) {
		super();
		this.id = id;
	}
	
	

	@Override
	public String toString() {
		return "Job [id=" + id + "]";
	}

	@Override
	public void run() {
		System.out.println(id + "   run..."  +  num.incrementAndGet());
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


class MyReject implements RejectedExecutionHandler{

	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		//executor.execute(r);
		System.out.println("被拒绝的任务为：   " + r.toString());
	}
	
}
